package com.bucks;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;

@Slf4j
@SpringBootApplication
public class SpringBucksReactorApplication implements ApplicationRunner {

    public static void main(String[] args) {
        SpringApplication.run(SpringBucksReactorApplication.class, args);
    }


    @Override
    public void run(ApplicationArguments args) throws Exception {
        Flux.range(1, 6)
                .doOnRequest(n -> log.info("发送 {} 请求", n))
                .publishOn(Schedulers.elastic())//publishOn()的顺序会影响操作的结果
                .doOnComplete(() -> log.info("完成后操作1"))
//                .publishOn(Schedulers.elastic())
                .map(integer -> {
                    log.info("发布 {},{}", Thread.currentThread(), integer);
                    return 10 / (integer - 3);
//                    return integer;
                })
                .doOnComplete(() -> log.info("完成后操作2"))
//                .subscribeOn(Schedulers.single())
                .onErrorResume(e -> {
                    log.error("Exception {}", e.toString());
                    return Mono.just(-1);
                })
//                .onErrorReturn(-1)
                .subscribe(integer -> log.info("订阅 {}; {}", Thread.currentThread(), integer),
                        e -> log.error("Error {}", e.toString()),
                        () -> log.info("全部完成"),
                        s -> s.request(4)
                );
        Thread.sleep(2000);
    }


}
